package com.glasses.orm.service;

import com.alibaba.fastjson.JSONObject;
import com.glasses.dao.IndentDao;
import com.glasses.dao.OrderDao;
import com.glasses.dao.UserDao;
import com.glasses.entity.Order;
import com.glasses.entity.User;
import com.glasses.orm.base.Ex.BaseServiceEx;
import com.glasses.orm.dictionary.Status;
import com.glasses.orm.utils.WXAppletUserInfo;
import com.glasses.orm.utils.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ashin on 2018/8/13.
 */
@Service
public class WxService extends BaseServiceEx {

    @Autowired
    WXAppletUserInfo wxAppletUserInfo;

    @Autowired
    OrderDao orderDao;

    @Autowired
    IndentDao indentDao;

    @Autowired
    UserDao userDao;

    //微信小程序登录
    public JSONObject login(Map map) throws Exception {
        JSONObject getSessionKeyOpenId = wxAppletUserInfo.getSessionKeyOropenid(map.get("code").toString());
        if (!getSessionKeyOpenId.containsKey("errcode")) {
            JSONObject userInfo = wxAppletUserInfo.getUserInfo(map.get("encryptedData").toString(), getSessionKeyOpenId.getString("session_key"), map.get("iv").toString());
            String openId = userInfo.getString("openId");
            Map userMap = new HashMap();
            userMap.put("openId",openId);
            User user = userDao.selectp(userMap);
            if(user == null) {
                userMap.put("nickName",userInfo.getString("nickName"));
                userMap.put("avatarUrl", userInfo.getString("avatarUrl"));
                userDao.insertp(userMap);
            }
            return this.codeData(userInfo);
        }
        return this.codeData(getSessionKeyOpenId);
    }
    /**
     * 微信支付回调
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public void payCallback(HttpServletRequest request, HttpServletResponse response) {
        logger.info("微信回调接口方法 start");
        logger.info("微信回调接口 操作逻辑 start");
        String inputLine = "";
        String notityXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            //关闭流
            request.getReader().close();
            logger.info("微信回调内容信息：" + notityXml);
            //解析成Map
            Map<String, String> map = WXPayUtil.xmlToMap(notityXml);
            //判断 支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                logger.info("微信回调返回是否支付成功：是");
                //获得 返回的商户订单号
                String outTradeNo = map.get("out_trade_no");
                logger.info("微信回调返回商户订单号：" + outTradeNo);
                //访问DB
                Map orderMap = new HashMap();
                orderMap.put("orderId", outTradeNo);
                Order order = orderDao.selectp(orderMap);
                logger.info("微信回调 根据订单号查询订单状态：" + order.getStatusVal());
                if (String.valueOf(Status.待付款).equals(String.valueOf(order.getStatus()))) {
                    //修改支付状态
                    orderMap.put("status", String.valueOf(Status.支付成功));
                    //更新Bean
                    int sqlRow = orderDao.updatep(orderMap);
                    indentDao.updatep(orderMap);
                    //判断 是否更新成功
                    if (sqlRow == 1) {
                        logger.info("微信回调  订单号：" + outTradeNo + ",修改状态成功");
                        //封装 返回值
                        String resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                + "<return_msg><![CDATA[OK]]></return_msg>"
                                + "</xml> ";
                        BufferedOutputStream out = new BufferedOutputStream(
                                response.getOutputStream());
                        out.write(resXml.getBytes());
                        out.flush();
                        out.close();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
